﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using mesoBoard.Data;
using mesoBoard.Data.Repositories;
using System.Drawing.Imaging;
using System.Drawing;

namespace mesoBoard.Services
{
    public class Polls : IPolls
    {
         
        private IRepositoriesWrapper Repositories;

        public Polls(IRepositoriesWrapper repos)
        {
            this.Repositories = repos;
        }

        public bool HasVoted(int pollID, int userID)
        {
            IEnumerable<PollVote> votes = Repositories.Polls.GetPollVotes(pollID);

            return votes.Any(x => x.PollOption.PollID == pollID && x.UserID == userID);
        }

        public void DeletePoll(int PollID)
        {
            Thread TheThread = Repositories.Threads.GetThread(PollID);
            Repositories.Polls.DeletePoll(PollID);
            TheThread.HasPoll = false;
            Repositories.Threads.UpdateThread(TheThread);
        }

        public void DeletePoll(Poll poll)
        {
            Thread thread = Repositories.Threads.GetThread(poll.PollID);
            Repositories.Polls.DeletePoll(poll);
            thread.HasPoll = false;
            Repositories.Threads.UpdateThread(thread);
        }

        public void CreatePoll(string pollQuestion, string pollOptions, int threadID)
        {
            string[] splitOptions = pollOptions.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            CreatePoll(pollQuestion, splitOptions, threadID);
        }

        public void CreatePoll(string pollQuestion, string[] pollOptions, int threadID)
        {
            System.Data.Objects.DataClasses.EntityCollection<PollOption>  toadd = new System.Data.Objects.DataClasses.EntityCollection<PollOption>();

            foreach (string po in pollOptions)
            {
                toadd.Add(new PollOption
                {
                    Text =  po,
                    PollID = threadID
                });
                    
            }

            Poll ThePoll = new Poll
            {
                PollOptions = toadd,
                Question =  pollQuestion,
                PollID = threadID
            };

            Repositories.Polls.CreatePoll(ThePoll);


            Thread TheThread = Repositories.Threads.GetThread(threadID);
            TheThread.HasPoll = true;
            Repositories.Threads.UpdateThread(TheThread);
        }
    }
}